package com.captcha.demo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.captcha.demo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2025-05-19
 * Time: 22:38
 */
@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private static final long CAPTCHA_TIME_OUT=30*60*1000;
    @Autowired
    private CaptchaProperties captchaProperties;
    @RequestMapping("/getCaptcha")
    public void CreateCaptcha(HttpSession session, HttpServletResponse response){
        try {
            LineCaptcha lineCaptcha= CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(),captchaProperties.getHeight());
            String code=lineCaptcha.getCode();
            session.setAttribute(captchaProperties.getSession().getCode(),code);
            session.setAttribute(captchaProperties.getSession().getTime(),System.currentTimeMillis());
            System.out.println("生成验证码:"+code);
            response.setContentType("image/jpeg");
            lineCaptcha.write(response.getOutputStream());
            response.getOutputStream().close();
        }catch (Exception a){
            System.out.println("发生异常"+a);
        }
    }

    @RequestMapping("/check")
    public boolean check(HttpSession session,String captcha){
        //验证是否为空
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        //检验是否超时和正确
        String captchaCode=(String) session.getAttribute(captchaProperties.getSession().getCode());
        Long captchaTime=(Long) session.getAttribute(captchaProperties.getSession().getTime());
        if (!StringUtils.hasLength(captchaCode)||captchaTime==null
                ||(System.currentTimeMillis()-captchaTime>CAPTCHA_TIME_OUT)){
            return false;
        }
        if (captcha.equalsIgnoreCase(captchaCode)){
            return true;
        }
        return false;
    }
}
